package org.halk.config;

import com.google.common.util.concurrent.ThreadFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;

import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 定时任务配置
 *
 * @Author halk
 * @Date 2023/7/20 15:19
 */
@Configuration
@EnableScheduling
public class ScheduleConfiguration implements SchedulingConfigurer {
    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        taskRegistrar.setScheduler(taskExecutor());
    }

    @Bean
    public ScheduledThreadPoolExecutor taskExecutor() {
        ThreadFactory threadFactory = new ThreadFactoryBuilder().setNameFormat("schedule-task-%d").build();
        ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(4, threadFactory);
        // 设置最大线程数
        executor.setMaximumPoolSize(10);
        // 设置线程活跃时间（秒）
        executor.setKeepAliveTime(10, TimeUnit.SECONDS);
        // 设置拒绝策略
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        return executor;
    }
}
